package com.qianxun.modular.base;

import lombok.Data;
import lombok.experimental.Accessors;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: huwei
 * @date: 2019/9/11 19:46
 * @version: 1.0.0
 */
@Data
@Accessors(chain = true)
public class Result<T> {
    /**
     * 固定字段
     * 描述：请求状态，true成功，false失败
     * 类型：boolean
     */
    private boolean status;
    /**
     * 可变字段，当status为false时出现
     * 描述：结果状态码信息
     * 类型：Integer
     */
    private Integer code;
    /**
     * 可变字段，当status为false时出现
     * 描述：消息提示
     * 类型：string
     */
    private String msg;
    /**
     * 可变字段，当status为true时，且该次请求有返回结果才返回
     * 描述：封装该次请求特有的返回结果；
     */
    private T data;

    /**
     * 静态工具
     */
    private Result() {
    }

    public Result(boolean status, Integer code, String msg, T data) {
        this.status = status;
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static Result success() {
        return success(null);
    }

    public static <T> Result success(T data) {
        return success(data, null);
    }

    public static <T> Result success(T data, String msg) {
        return buildSuccess().setMsg(msg).setData(data);
    }

    public static <T> Result successList(List<T> list) {
        Map<String, Object> res = new HashMap<>(2);
        res.put("records", list);
        return buildSuccess().setData(res);
    }

    public static <T> Result successPage(List<T> list, long total, long current, long size) {
        Map<String, Object> res = new HashMap<>(8);
        res.put("records", list);
        res.put("total", total);
        res.put("current", current);
        res.put("size", size);
        return success(res);
    }

    public static Result fail(String msg) {
        return fail(500, msg);
    }

    public static Result fail(Integer code, String msg) {
        return fail(code, msg, null);
    }

    public static <T> Result fail(Integer code, String msg, T data) {
        return new Result().setStatus(false).setCode(code).setMsg(msg).setData(data);
    }

    private static Result buildSuccess() {
        return new Result(true, 200, null, null);
    }
}
